<template>
  <el-dialog
    class="device-selector"
    :visible="visible"
    :before-close="handleClose"
    :title="config.title"
    :close-on-click-modal="false"
  >
    <QueryContainer @search="findGroupPageByParam" @reset="handleReset">
      <el-form
        ref="queryForm"
        inline
        :model="queryInfo"
        label-position="left"
        :label-width="handleScreenWidthToVw(90) + 'px'"
        class="justify-between"
      >
        <div>
          <el-form-item label="所属产品" prop="productId">
            <SelectProduct
              ref="SelectProduct"
              :style="{width: handleScreenWidthToVw(200) + 'px'}"
              @change="({id})=>queryInfo.productId=id"
            />
          </el-form-item>
          <el-form-item label="在线状态" prop="enableStateEnum">
            <SelectOnlineState
              ref="SelectOnlineState"
              v-model="queryInfo.enableStateEnum"
              :style="{width: handleScreenWidthToVw(200) + 'px'}"
            />
          </el-form-item>
          <el-form-item label="" prop="keyword">
            <el-input
              v-model="queryInfo.keyword"
              placeholder="请输入设备名或备注名称"
              clearable
              :style="{width: handleScreenWidthToVw(200) + 'px'}"
            >
              <i slot="suffix" class="el-input__icon el-icon-search" />
            </el-input>
          </el-form-item>
        </div>
      </el-form>
    </QueryContainer>
    <div style="border: 1px solid #CCC;">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        header-cell-class-name="table-header-cell"
        header-row-class-name="table-header-row"
        class="table-container flex-sub"
        height="50vh"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="45" align="center" />
        <el-table-column label="设备名/备注名称">
          <template v-slot="{row}">
            <div>{{ row.name }}</div>
            <div>{{ row.remarkName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="所属产品">
          <template v-slot="{row}">
            <div>{{ row.productVo && row.productVo.name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="在线状态">
          <template v-slot="{row:{online}}">
            <span class="online-state" :style="{color:( online?'#0084EE':'#D12D1F')}">
              {{ online ? '在线' : '离线' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="最近上线时间">
          <template v-slot="{row}">
            <span>{{ row.activeTime || row.createTime | dateTimeFormatter }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="mg-bottom-18"
        hide-on-single-page
        background
        layout="prev, pager, next, total, jumper"
        :total="queryInfo.total"
        :page-size="queryInfo.pageSize"
        @current-change="handlePageNoChange"
      />
    </div>
    <div slot="footer" class="justify-between w-100P">
      <span>
        已选择
        <span class="fz-20 mg-lr-4" style="color: #D12D1F;">{{ selectedDevicesList.length }}</span>
        个设备
      </span>
      <span>
        <el-button type="primary" @click="handleConfirm">
          {{ config.confirmButtonText || '确认' }}
        </el-button>
        <el-button @click="handleClose">{{ config.cancelButtonText || '取消' }}</el-button>
      </span>
    </div>
  </el-dialog>
</template>

<script>
import SelectProduct from '../select-product/select-product'
import SelectOnlineState from '../select-states/select-device-online-state'
import QueryContainer from '@/components/query-container'

import { apiFindDevicePageByParam } from '@/components/device-selector/api'
import { handleScreenWidthToVw } from '@/utils/tools'

const defaultConfig = {
  title: '设备选择器',
  confirmButtonText: '提交',
  cancelButtonText: '取消',
  unGatewayId: '', // 需要排除的网关id
  unGroupId: '', // 需要排除的分组id
}
export default {
  name: 'DeviceSelector',
  components: {
    // SelectDeviceState,
    SelectOnlineState,
    // SelectNetType,
    SelectProduct,
    QueryContainer,
  },
  props: {
    visible: { type: Boolean, required: true, default: false },
    config: { type: Object, required: false, default: defaultConfig },
  },
  data() {
    return {
      loading: false,
      queryInfo: {
        /**
         * @type {'EXTERNAL','INTERNAL'} deviceSourceEnum
         */
        // online: true,
        // 启用状态
        enableStateEnum: '',
        // 所属产品id
        productId: '',
        // 入网类型
        netType: '',
        keyword: '',
        pageSize: 10,
        pageNo: 1,
        total: 0,
      },
      tableData: [],
      selectedDevicesList: [],
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(value) {
        if (value) {
          this.initData()
        }
      },
    },
  },
  computed: {
    handleScreenWidthToVw() {
      return handleScreenWidthToVw
    },
  },
  methods: {
    async initData() {
      await this.findGroupPageByParam()
    },

    handleClose() {
      this.$emit('update:visible', false)
    },
    handleReset() {
      this.$refs.queryForm.resetFields()
      this.$refs.SelectProduct.handleReset()
      this.$refs.SelectOnlineState.handleReset()
      this.findGroupPageByParam()
    },
    handleConfirm() {
      this.$emit('confirm', this.selectedDevicesList)
      this.handleClose()
    },
    handlePageNoChange(pageNo) {
      this.queryInfo.pageNo = pageNo
      this.findGroupPageByParam()
    },
    handleSelectionChange(selectChange) {
      this.selectedDevicesList = selectChange
      this.$emit('select-change', selectChange)
    },
    async findGroupPageByParam() {
      this.loading = true
      const formData = {}
      for (const key in this.queryInfo) {
        if (this.queryInfo[key] && this.queryInfo[key].toString().length) {
          formData[key] = this.queryInfo[key]
        }
      }
      if (this.config.unGroupId) {
        formData['unGroupId'] = this.config.unGroupId
      }
      if (this.config.excludeBusinessTypeEnum) {
        formData['excludeBusinessTypeEnum'] = this.config.excludeBusinessTypeEnum
      }
      if (formData['enableStateEnum']) {
        formData['online'] = formData['enableStateEnum'] === 'ONLINE'
      }
      formData['enableStateEnum'] = undefined
      const { records, total } = await apiFindDevicePageByParam(formData)
      this.queryInfo.total = total
      this.tableData = records
      this.loading = false
    },
  },
}
</script>

<style scoped lang="scss">
.device-selector {
  .online-state {
    &.OFFLINE,
    &.ONLINE {
      position: relative;

      &::after {
        display: inline-block;
        width: 10px;
        height: 10px;
        margin-left: 10px;
        border-radius: 50%;
        content: '';
      }
    }
  }

  .table-container {
    margin-top: 0;
    border: none;
  }

  ::v-deep .el-dialog__body {
    padding-top: 0;
    padding-bottom: 0;
  }
}
</style>
